package com.lzy.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzy.dao.SysUserDao;
import com.lzy.entity.SysPostEntity;
import com.lzy.entity.SysRoleEntity;
import com.lzy.entity.SysUserEntity;
import com.lzy.service.ISysPostService;
import com.lzy.service.ISysRoleDeptService;
import com.lzy.service.ISysRoleService;
import com.lzy.utils.StringUtil;
import com.lzy.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysRoleDeptService iSysRoleDeptService;

    @Autowired
    private ISysPostService iSysPostService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUserEntity user = sysUserDao.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name", username));
        if (Objects.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new RuntimeException("登录用户：" + username + " 不存在");
        }
        user.setPassword(passwordEncoder.encode("123456"));

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUserEntity user) {
        LoginUser loginUser =
                new LoginUser(user.getUserId(),
                        user,
                        null);
        // 当前用户的角色信息
        Set<SysRoleEntity> roles = selectUserRoles(user.getUserId());
        boolean admin = UserUtil.isAdmin(roles.stream().map(item -> item.getRoleKey()).collect(Collectors.toSet()));
        // 不是管理员
        if (!admin) {
            // 获取部门的角色信息
            Set<SysRoleEntity> deptRoles = iSysRoleDeptService.selectDeptRoleInfo(user.getDeptId());
            if (!StringUtil.isNull(deptRoles)) {
                roles.addAll(deptRoles);
            }
        }
        user.setRoles(roles);
        // 获取岗位信息
        List<SysPostEntity> postEntities = iSysPostService.getCurUserPostInfo(user.getUserId());
        user.setPosts(postEntities);
        // 获取当前用户的所有权限信息
        Set<String> permissions = iSysRoleService.selectUserPermission(roles);
        loginUser.setPermissions(permissions);
        loginUser.setRoles(roles.stream().map(item -> item.getRoleKey()).collect(Collectors.toSet()));
        return loginUser;
    }

    public Set<SysRoleEntity> selectUserRoles(Long userId) {

        return new HashSet<>(iSysRoleService.selectUserRoles(userId));
    }
}
